package com.example.zhidao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.zhidao.model.po.Cgoods;
import com.example.zhidao.model.responseData.ResponseData;
import com.example.zhidao.service.CgoodsService;
import com.example.zhidao.utils.Ujwt;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/cgoods")
public class CgoodsController {//2

    @Autowired
    CgoodsService cgoodsService;

    @Autowired
    Ujwt ujwt;

//    评论点赞
    @PostMapping("/add")
    public ResponseData addCgoods(@RequestHeader("token") String token,String cid){

        //        解token
        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
        String uid=claims.getId();

        QueryWrapper<Cgoods> qw=new QueryWrapper<>();
        qw.eq("uid",uid);
        qw.eq("cid",cid);

        Cgoods c=cgoodsService.getOne(qw);

        if(c!=null){
            return new ResponseData(null,true,"你已经点过赞了",201);
        }else{
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");//自动生成uuid
            Cgoods cgoods=new Cgoods();
            cgoods.setId(uuid);
            cgoods.setCid(cid);
            cgoods.setUid(uid);
            boolean i=cgoodsService.addcgood(cgoods);

            if(i){
                return new ResponseData(i,true,"点赞成功",200);
            }else{
                return new ResponseData(i,false,"点赞失败",202);
            }
        }
    }

//    取消点赞
    @DeleteMapping("/del")
    public ResponseData delCgood(@RequestHeader("token") String token,String cid){
        //        解token
        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
        String uid=claims.getId();

        QueryWrapper<Cgoods> qw=new QueryWrapper<>();
        qw.eq("uid",uid);
        qw.eq("cid",cid);

        Cgoods c=cgoodsService.getOne(qw);

        if(c!=null){
            boolean i=cgoodsService.delcgood(c);
            if(i){
                return new ResponseData(i,true,"取消点赞",200);
            }else{
                return new ResponseData(i,true,"取消点赞",200);
            }
        }else{
            return new ResponseData(null,false,"你未曾点赞",201);
        }
    }
}
